<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Storage;

class File extends Model
{
    protected $fillable = ['md5', 'users_id', 'path', 'url', 'engine', 'file_name', 'size', 'content_type', 'extension'];

    public static function createFile(UploadedFile $uploadedFile, int $users_id = null, string $engine = 'public')
    {
        $fileMd5 = md5_file($uploadedFile->path());
        $file = static::whereMd5($fileMd5)->first();
        if (!empty($file)) {
            return $file;
        }
        $disk = Storage::disk($engine);
        $fileName = $fileMd5 . '.' . $uploadedFile->extension();
        $date = date('ymd') . DIRECTORY_SEPARATOR;
        $filePath = $date . $fileName;
        $disk->put($filePath, fopen($uploadedFile->path(), 'r+'));
        return static::create([
            'md5' => $fileMd5,
            'users_id' => $users_id,
            'path' => $filePath,
            'url' => '/api/file/image/' . $fileMd5,
            'engine' => $engine,
            'file_name' => $uploadedFile->getClientOriginalName(),
            'size' => $uploadedFile->getSize(),
            'content_type' => $uploadedFile->getMimeType(),
            'extension' => $uploadedFile->extension()
        ]);
    }
}
